<template>
  <div class="app-container">
    <div class="header">
      <h1>编辑项目信息</h1>
    </div>
    
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="form-container">
      <!-- 项目基本信息 -->
      <h3 class="section-title">项目基本信息</h3>
      <el-form-item label="项目名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入项目名称" style="width: 400px;"></el-input>
      </el-form-item>
      
      <el-form-item label="项目简介" prop="description">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入项目简介"
          v-model="form.description"
          style="width: 600px;"
          maxlength="500"
          show-word-limit>
        </el-input>
      </el-form-item>
      
      <el-form-item label="部署方式" prop="deployMethod">
        <el-radio-group v-model="form.deployMethod">
          <el-radio label="manual">手动执行</el-radio>
          <el-radio label="auto">自动执行</el-radio>
        </el-radio-group>
      </el-form-item>
    
      
      <!-- 资源配额 -->
      <h3 class="section-title">资源配额</h3>
      <el-form-item label="CPU配额" prop="cpuQuota">
        <div class="quota-item">
          <el-input-number v-model="form.cpuQuota" :min="0.1" :max="32" :step="0.1" label="CPU配额"></el-input-number>
          <span style="margin-left: 10px;">核心</span>
        </div>
      </el-form-item>
      
      <el-form-item label="内存配额" prop="memoryQuota">
        <div class="quota-item">
          <el-input-number v-model="form.memoryQuota" :min="128" :max="65536" :step="128" label="内存配额"></el-input-number>
          <span style="margin-left: 10px;">MB</span>
        </div>
      </el-form-item>
      
      <el-form-item label="存储配额" prop="storageQuota">
        <div class="quota-item">
          <el-input-number v-model="form.storageQuota" :min="1" :max="1024" :step="1" label="存储配额"></el-input-number>
          <span style="margin-left: 10px;">GB</span>
        </div>
      </el-form-item>
      
      <el-form-item label="GPU配额" prop="gpuQuota">
        <div class="quota-item">
          <el-input-number v-model="form.gpuQuota" :min="0" :max="8" :step="1" label="GPU配额"></el-input-number>
          <span style="margin-left: 10px;">个</span>
        </div>
      </el-form-item>
      
      <el-form-item label="显存配额" prop="gpuMemoryQuota">
        <div class="quota-item">
          <el-input-number v-model="form.gpuMemoryQuota" :min="0" :max="32768" :step="1024" label="显存配额"></el-input-number>
          <span style="margin-left: 10px;">MB</span>
        </div>
      </el-form-item>
      
      <!-- 环境变量 -->
      <h3 class="section-title">环境变量</h3>
      <el-form-item label="环境变量">
        <div v-for="(env, index) in form.environmentVariables" :key="index" class="env-variable-item">
          <el-input v-model="env.key" placeholder="变量名" style="width: 200px;"></el-input>
          <el-input v-model="env.value" placeholder="变量值" style="width: 300px;"></el-input>
          <el-button @click.prevent="removeEnvVariable(index)" type="danger" icon="el-icon-delete" circle></el-button>
        </div>
        <el-button @click="addEnvVariable" type="primary" icon="el-icon-plus">添加环境变量</el-button>
      </el-form-item>
      
      <el-form-item label="运行指令" prop="runCommand">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入运行指令，例如：npm start"
          v-model="form.runCommand"
          style="width: 600px;">
        </el-input>
      </el-form-item>
      
      <!-- 操作按钮 -->
      <div class="footer-buttons">
        <el-button type="primary" @click="onSubmit" :loading="loading">保存修改</el-button>
        <el-button @click="onCancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { getTaskById, updateTask } from "@/api/package/task";
import { listBaseImages } from "@/api/package/image";

export default {
  name: 'ProjectEdit',
  data() {
    return {
      loading: false,
      fileList: [],
      projectId: null,
      
      form: {
        name: '',
        description: '',
        deployMethod: 'manual',
        
        cpuQuota: 1.0,
        memoryQuota: 512,
        storageQuota: 10,
        gpuQuota: 0,
        gpuMemoryQuota: 0,
        environmentVariables: [
          { key: '', value: '' }
        ],
        runCommand: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
        ],
        deployMethod: [
          { required: true, message: '请选择部署方式', trigger: 'change' }
        ],
        cpuQuota: [
          { required: true, message: '请输入CPU配额', trigger: 'blur' }
        ],
        memoryQuota: [
          { required: true, message: '请输入内存配额', trigger: 'blur' }
        ],
        storageQuota: [
          { required: true, message: '请输入存储配额', trigger: 'blur' }
        ],
        runCommand: [
        ]
      }
    };
  },
  created() {
    this.loadRouteData();
  },
  watch: {
    '$route': {
      handler: 'loadRouteData',
      immediate: true
    }
  },
  methods: {
    // 加载路由数据
    loadRouteData() {
      const newProjectId = this.$route.params.id;
      console.log('路由参数id:', newProjectId);
      console.log('完整路由信息:', this.$route);
      
      // 只有当项目ID发生变化时才重新加载数据
      if (newProjectId && newProjectId !== this.projectId) {
        this.projectId = newProjectId;
        this.loadProjectData();
      } else if (!newProjectId) {
        console.error('未获取到项目ID');
        this.$message.error('未获取到项目信息');
      }
    },
    // 加载项目数据
    async loadProjectData() {
      try {
        this.loading = true;
        console.log('开始加载项目数据，项目ID:', this.projectId);
        
        const response = await getTaskById(this.projectId);
        console.log('API响应原始数据:', response);
        
        // 处理API响应数据 - 根据请求拦截器的处理逻辑
        let projectData = null;
        if (response && response.code === 200 && response.task) {
          // 标准响应结构：{ code: 200, task: { ... } }
          projectData = response.task;
          console.log('使用task结构，数据:', projectData);
        } else if (response && response.code === 200 && response.data) {
          // 标准响应结构：{ code: 200, data: { ... } }
          projectData = response.data;
          console.log('使用data结构，数据:', projectData);
        } else if (response && response.data) {
          // 结构：{ data: { ... } }
          projectData = response.data;
          console.log('使用data结构，数据:', projectData);
        } else {
          // 直接返回数据
          projectData = response;
          console.log('使用直接返回数据:', projectData);
        }
        
        console.log('处理后的项目数据:', projectData);
        
        if (!projectData) {
          console.error('项目数据为空');
          this.$message.error('未获取到项目数据');
          return;
        }
        
        // 检查关键字段是否存在
        console.log('项目数据字段检查:', {
          name: projectData.name,
          description: projectData.description,
          type: projectData.type,
          cpu: projectData.cpu,
          memory: projectData.memory,
          storage: projectData.storage,
          gpu: projectData.gpu,
          gpuMemory: projectData.gpuMemory,
          environmentVars: projectData.environmentVars,
          runCommands: projectData.runCommands
        });
        
        // 使用 Vue.set 或逐个属性赋值确保响应式更新
        // 逐个更新表单属性，确保响应式系统能够检测到变化
        this.form.name = projectData.name || '';
        this.form.description = projectData.description || '';
        this.form.deployMethod = projectData.type === 'code' ? 'auto' : 'manual';
        this.form.cpuQuota = projectData.cpu || 1.0;
        this.form.memoryQuota = projectData.memory || 512;
        this.form.storageQuota = projectData.storage || 10;
        this.form.gpuQuota = projectData.gpu || 0;
        this.form.gpuMemoryQuota = projectData.gpuMemory || 0;
        
        // 对于数组类型，需要重新赋值以确保响应式更新
        this.form.environmentVariables = projectData.environmentVars && projectData.environmentVars.length > 0 
          ? [...projectData.environmentVars] 
          : [{ key: '', value: '' }];
        
        this.form.runCommand = projectData.runCommands && projectData.runCommands.length > 0 
          ? projectData.runCommands[0].command 
          : '';
        
        console.log('映射后的表单数据:', this.form);
        console.log('当前表单状态:', {
          name: this.form.name,
          description: this.form.description,
          deployMethod: this.form.deployMethod,
          cpuQuota: this.form.cpuQuota,
          memoryQuota: this.form.memoryQuota
        });
        
        // 强制更新视图以确保DOM重新渲染
        this.$nextTick(() => {
          this.$forceUpdate();
        });
        
        // 检查表单是否成功绑定
        setTimeout(() => {
          console.log('延迟检查表单绑定状态:', {
            formName: this.form.name,
            formDescription: this.form.description,
            formDeployMethod: this.form.deployMethod
          });
        }, 100);
        
        this.$message.success('项目数据加载成功');
      } catch (error) {
        console.error('加载项目数据失败:', error);
        console.error('错误详情:', error.response || error);
        console.error('错误状态码:', error.response?.status);
        console.error('错误响应数据:', error.response?.data);
        this.$message.error('加载项目数据失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },

    // 提交表单
    async onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            
            // 获取当前登录用户信息
            const userInfo = JSON.parse(localStorage.getItem("honey-user") || '{}');
            
            // 准备提交数据 - 添加部署方式字段
            const submitData = {
              id: this.projectId,
              name: this.form.name,
              description: this.form.description,
              type: this.form.deployMethod === 'auto' ? 'code' : 'image',
              deployType: this.form.deployMethod, // 添加部署方式字段
              cpu: this.form.cpuQuota,
              memory: this.form.memoryQuota,
              storage: this.form.storageQuota,
              gpu: this.form.gpuQuota,
              gpuMemory: this.form.gpuMemoryQuota,
              environmentVars: this.form.environmentVariables.filter(env => env.key.trim() !== '' && env.value.trim() !== ''),
              runCommands: this.form.runCommand.trim() !== '' ? [{ command: this.form.runCommand }] : [],
              // 添加用户ID
              updaterId: userInfo.id
            };

            console.log('提交的数据:', submitData);
            console.log('部署方式字段 deployType:', submitData.deployType);

            await updateTask(submitData);
            
            this.$message({
              message: '项目信息保存成功',
              type: 'success'
            });
            
            // 保存成功后返回列表页
            this.$router.push('/task');
          } catch (error) {
            console.error('保存项目失败:', error);
            console.error('错误详情:', error.response || error);
            this.$message.error('保存项目失败');
          } finally {
            this.loading = false;
          }
        } else {
          this.$message.error('请检查表单填写是否正确');
          return false;
        }
      });
    },
    onCancel() {
      this.$confirm('确定要取消编辑吗？所有未保存的更改将丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'info',
          message: '已取消编辑'
        });
        // 跳转到任务列表页面
        this.$router.push('/task');
      }).catch(() => {
        // 用户点击了取消按钮，不做任何操作
      });
    },
    addEnvVariable() {
      this.form.environmentVariables.push({
        key: '',
        value: ''
      });
    },
    removeEnvVariable(index) {
      this.form.environmentVariables.splice(index, 1);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
.header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6ebf5;
}
.header h1 {
  color: #303133;
  margin: 0;
}
.form-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.section-title {
  font-size: 16px;
  color: #303133;
  margin: 20px 0 15px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}
.quota-item {
  display: inline-block;
  width: 48%;
  margin-right: 4%;
  margin-bottom: 15px;
}
.quota-item:nth-child(2n) {
  margin-right: 0;
}
.env-variable-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.env-variable-item .el-input {
  margin-right: 10px;
}
.footer-buttons {
  margin-top: 30px;
  text-align: center;
}
.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}
.file-list {
  margin-top: 10px;
}
@media (max-width: 768px) {
  .quota-item {
    width: 100%;
    margin-right: 0;
  }
}
</style>
